package com.xtaller.easy.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.common.convert.V;
import com.xtaller.easy.admin.async.CacheSysTask;
import com.xtaller.easy.admin.base.TServiceImpl;
import com.xtaller.easy.admin.config.Constant;
import com.xtaller.easy.admin.mapper.SysDictMapper;
import com.xtaller.easy.admin.model.SysDict;
import com.xtaller.easy.admin.service.ISysDictService;
import com.xtaller.easy.admin.tps.CacheKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import com.xtaller.common.convert.W;
import com.xtaller.common.bean.Where;
/**
* Created by Taller on 2018/04/13
*/
@Service
public class SysDictService extends TServiceImpl<SysDictMapper,SysDict> implements ISysDictService {
    @Autowired
    private CacheKit cacheKit;
    @Autowired
    @Lazy
    private CacheSysTask cacheSysTask;

    /**************************CURD begin******************************/
   // 创建
   @Override
   public SysDict createSysDict(SysDict model) {
       if(this.insert(model)) {
           cacheSysTask.cacheDict();
           return this.selectById(model.getId());
       }
       return null;
   }
 
   // 删除
   @Override
   public Boolean deleteSysDict(Object ids,String reviser) {
       Boolean opt = this.delete(ids,reviser);
       cacheSysTask.cacheDict();
       return opt;
   }
 
   // 修改
   @Override
   public SysDict updateSysDict(SysDict model) {
       if(this.update(model)) {
           cacheSysTask.cacheDict();
           return this.selectById(model.getId());
       }
       return null;
   }
 
   // 查询
   @Override
   public List<SysDict> findByIds(Object ids) {
       return this.selectByIds(ids);
   }
 
   // 属于
   @Override
   public Boolean exist(List<Where> w) {
       w.add(new Where("1"));
       return this.query(w).size() > 0;
   }
 
   // 查询一个id是否存在
   @Override
   public Boolean existId(Object id) {
       where = W.f(
               W.and("id","eq",id),
               W.field("1")
       );
       return this.query(where).size() > 0;
   }

    /**************************CURD end********************************/
    @Override
    public Boolean existCode(SysDict model, boolean isCreate) {
        if(!isCreate){
            where = W.f(
                    W.and("code", "eq", model.getCode()),
                    W.and("parentId", "eq", model.getParentId() == null ? 0 : model.getParentId()),
                    W.and("id", "ne", model.getId())
            );
        }else{
            where = W.f(
                    W.and("code", "eq", model.getCode()),
                    W.and("parentId", "eq", model.getParentId() == null ? 0 : model.getParentId())
            );
        }
        return this.queryOne(where) == null ? false : true;
    }

    @Override
    public Boolean existModule(SysDict model, boolean isCreate) {
        if(!isCreate){
            where = W.f(
                    W.and("name", "eq", model.getName()),
                    W.and("id", "ne", model.getId()),
                    W.and("moduleId", "eq", 0)
            );
        }else{
            where = W.f(
                    W.and("name", "eq", model.getName()),
                    W.and("moduleId", "eq", 0)
            );
        }
        return this.queryOne(where) == null ? false : true;
    }

    @Override
    public Boolean existName(SysDict model, boolean isCreate) {
        if(!isCreate){
            where = W.f(
                    W.and("name", "eq", model.getName()),
                    W.and("id", "ne", model.getId()),
                    W.and("parentId", "eq", model.getParentId())
            );
        }else{
            where = W.f(
                    W.and("name", "eq", model.getName()),
                    W.and("parentId", "eq", model.getParentId())
            );
        }
        return this.queryOne(where) == null ? false : true;
    }

    @Override
    public List<SysDict> getModule() {
        where = W.f(
                W.and("moduleId", "eq", 0),
                W.field("id", "name", "code", "sort"),
                W.order("sort", "asc")
        );
        return this.query(where);
    }

    @Override
    public List<SysDict> getByModuleId(Long moduleId) {
        where = W.f(
                W.and("moduleId", "eq", moduleId),
                W.field("id", "name", "code", "sort", "parentId"),
                W.order("sort", "asc")
        );
        return this.query(where);
    }

    @Override
    public List<SysDict> getByModuleIdOrParentId(String id) {
        return baseMapper.getByModuleIdOrParentId(id);
    }

    @Override
    public List<JSONObject> getInByCode(String[] code) {
        // 处理字符串成sql格式
        String[] data = new String[code.length];
        for(int i=0;i<code.length;i++){
            data[i] = "'" + code[i] + "'";
        }
        return baseMapper.getDictInByCode(String.join(",", data));
    }

    @Override
    public JSONObject getAllDict() {
        JSONObject cache = cacheKit.getObject(Constant.CACHE_SYS_DICT);
        if(cache == null){
            cache = cacheAllDict();
            cacheKit.setVal(Constant.CACHE_SYS_DICT, cache);
        }
        return cache;
    }

    @Override
    public JSONObject getDictByCode() {
        return getAllDict();
    }


    private JSONObject cacheAllDict(){
        where = W.f(
                W.field("id", "name", "code", "sort", "parentId"),
                W.order("sort", "asc")
        );
        List<SysDict> dicts = this.query(where);
        JSONObject data = new JSONObject();
        // 先找到父级
        List<SysDict> parents = new ArrayList<>();
        if(dicts.size() > 0){
            for(SysDict dict:dicts){
                if(V.isEqual(dict.getParentId(), "0")){
                    parents.add(dict);
                }
            }
            // 遍历子集组装新数据
            for(SysDict parent:parents){
                List<JSONObject> subs = new ArrayList<>();
                for(SysDict dict:dicts){
                    if(V.isEqual(dict.getParentId(), parent.getId())){
                        JSONObject object = new JSONObject();
                        object.put("code", dict.getCode());
                        object.put("name", dict.getName());
                        subs.add(object);
                    }
                }
                data.put(parent.getCode(), subs);
            }
        }
        return data;
    }

    public void updateCache(){
        cacheKit.setVal(Constant.CACHE_SYS_DICT, cacheAllDict());
    }
}